import { useState, useEffect } from "react";
import ReactEcharts from "echarts-for-react";

function Home() {
  const [options, setOptions] = useState({});

  let nodeIndex = 0;

  const rotate = (center, distance, theta) => {
    let p = {
      x: center.x + distance,
      y: center.y,
    };
    var _x =
      (p.x - center.x) * Math.cos(theta) -
      (p.y - center.y) * Math.sin(theta) +
      center.x;
    var _y =
      (p.x - center.x) * Math.sin(theta) +
      (p.y - center.y) * Math.cos(theta) +
      center.y;
    return { x: _x, y: _y };
  };

  const handleHost = (nodes, links, host, center) => {
    let hostNode = {
      id: nodeIndex++,
      name: `${host.Name}[${host.Ip}]`,
      symbolSize: 50,
      value: 0,
      category: 0,
      x: center.x,
      y: center.y,
    };
    nodes.push(hostNode);
    if (host.Nodes) {
      let tempIndex = 0;
      let theta = (Math.PI * 2) / host.Nodes.length;
      for (let node of host.Nodes) {
        let p = rotate(center, 10, theta * tempIndex++);
        let nodeNode = {
          id: nodeIndex++,
          name: `${node.Name}[${node.Ip}]`,
          symbolSize: 30,
          value: node.Delay,
          category: node.Name ? 1 : 2,
          x: p.x,
          y: p.y,
        };
        nodes.push(nodeNode);
        links.push({
          source: hostNode.id,
          target: nodeNode.id,
        });

        if (node.Nodes) {
          handleHost(nodes, links, node, p);
        }
      }
    }
  };

  const drawChart = (host) => {
    let categories = [
      {
        name: "Host",
      },
      {
        name: "Peer",
      },
      {
        name: "Other",
      },
    ];

    let center = {
      x: -266,
      y: 299,
    };
    let nodes = [];
    let links = [];

    handleHost(nodes, links, host, center);

    let option = {
      title: {
        text: "Ping Topology",
        top: "bottom",
        left: "right",
      },
      tooltip: {},
      legend: [
        {
          data: categories.map((item) => item.name),
        },
      ],
      animationDuration: 1500,
      animationEasingUpdate: "quinticInOut",
      series: [
        {
          type: "graph",
          legendHoverLink: false,
          layout: "none",
          data: nodes,
          links: links,
          categories: categories,
          roam: true,
          label: {
            position: "right",
            formatter: "{b}",
          },
          lineStyle: {
            color: "source",
            curveness: 0.3,
          },
          emphasis: {
            focus: "adjacency",
            lineStyle: {
              width: 10,
            },
          },
        },
      ],
    };
    setOptions(option);
  };

  const fetchHosts = async () => {
    const res = await fetch("/api/host.json");
    if (res.ok) {
      const host = await res.json();
      drawChart(host);
    }
  };

  useEffect(() => {
    let intervalId = null;
    fetchHosts();

    intervalId = setInterval(() => {
      fetchHosts();
    }, 60000);

    return () => clearInterval(intervalId);
  }, []);

  return (
    <>
      <ReactEcharts
        option={options} // option：图表配置项
        // onEvents={onEvents}
        notMerge={true}
        lazyUpdate={true}
        style={{ height: "80vh" }}
      />
    </>
  );
}

export default Home;
